<template>
  <div class="login-page">
    <div class="login">
      <div class="logo">
        <el-icon class="icon">
          <StarFilled />
        </el-icon>
        <h2>后台管理系统</h2>
      </div>
      <p>注册新用户</p>
      <el-form label-width="auto" style="max-width: 400px;">
        <el-form-item>
          <el-input v-model="username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item>
          <el-input v-model="confirmPassword" type="password" placeholder="请确认密码" show-password />
        </el-form-item>
        <el-form-item>
          <el-button class="register-btn" type="primary" round @click="handleRegister">注册</el-button>
        </el-form-item>
        <el-form-item>
          <el-button class="log-button" @click="goToLogin">返回登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElNotification } from 'element-plus';
import api from '@/utils/axios';
import { StarFilled } from '@element-plus/icons-vue';

const username = ref('');
const password = ref('');
const confirmPassword = ref('');
const router = useRouter();

const handleRegister = async () => {
  if (password.value !== confirmPassword.value) {
    ElNotification({
      title: '注册失败',
      message: '两次输入的密码不一致',
      type: 'error'
    });
    return;
  }

  try {
    const response = await api.post('/auth/register', {
      username: username.value,
      password: password.value
    });
    ElNotification({
      title: '注册成功',
      message: '欢迎加入！',
      type: 'success'
    });
    router.push('/'); // 注册成功后跳转到登录页面
  } catch (error) {
    console.log(error);
    
    ElNotification({
      title: '注册失败',
      message: '用户名已存在或注册失败',
      type: 'error'
    });
  }
};

const goToLogin = () => {
  router.push('/'); // 返回登录页面
};
</script>

<style scoped>
.login-page {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(to right, #5fb0f8, #00f2fe);
}

.login {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.logo {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 20px;
  color: #0ba9b1;
}

.icon {
  font-size: 40px;
  margin: 10px;
}

p {
  padding: 0px;
  font-size: 14px;
  color: #09d0da;
}

.register-btn {
  width: 100%;
}

.log-button {
  width: 100%;
}
</style>